<template>
  <div id="uploadcontent">
    <my-steps :active="stepactive"></my-steps>
    <div class="write" v-if="stepactive == 1">
      <div class="blockname">基础信息</div>
      <ul>
        <li>
          <div class="fill-title">文档标题：</div>
          <div class="fill-input">
            <el-input size="small" v-model="knowledgeName" placeholder></el-input>
          </div>
        </li>
        <li>
          <div class="fill-title">作者：</div>
          <div class="fill-show">{{user.admin || user.realName || user.userName}}</div>
        </li>
        <li>
          <div class="fill-title">所属部门：</div>
          <div class="fill-show">{{obj.regionName}}</div>
        </li>
        <!-- <li>
          <div class="fill-title">所属岗位：</div>
          <div class="fill-show">系统管理员</div>
                </li>-->
        <li>
          <div class="fill-title">知识分类：</div>
          <div class="fill-input">
            <el-cascader ref="knowledgeCategory" size="small" v-model="gettype" separator="-" :options="category" :props="defaultPropscategary" placeholder="请选择" style="width:100%;" @change="choosetype"></el-cascader>
          </div>
        </li>
        <li>
          <div class="fill-title">知识属性：</div>
          <div class="fill-input">
            <el-select v-model="knowledgeType" size="small" style="width:100%;">
              <el-option label="普通" :value="0"></el-option>
              <el-option label="热点" :value="1"></el-option>
              <el-option label="其它" :value="2"></el-option>
            </el-select>
          </div>
        </li>
        <li>
          <div class="fill-title">审批人：</div>
          <div class="fill-input">
            <el-select v-model="knowledgeExamineUserId" size="small" style="width:100%;">
              <el-option v-for="(item,index) in approver" :key="index" :label="item.admin||item.realName||item.userName" :value="item.userId"></el-option>
            </el-select>
          </div>
        </li>
        <li>
          <div class="fill-title">过期时间：</div>
          <div class="fill-input">
            <el-date-picker v-model="knowledgePastTime" size="small" type="date" value-format="yyyy-MM-dd 23:59:59" placeholder="文档达到过期时间归为过期文档" style="width:100%;" :picker-options="pickerOptions"></el-date-picker>
          </div>
        </li>
        <li class="textarea">
          <div class="fill-title">内容摘要：</div>
          <div class="fill-input">
            <el-input type="textarea" :rows="5" maxlength="300" show-word-limit size="small" v-model="knowledgeDesc" placeholder="不得超过300字"></el-input>
          </div>
        </li>
        <li style="margin-top:10px;">
          <div class="fill-title">文档附件：</div>
          <div class="fill-input">
            <el-upload class="upload-demo" ref="upload" action="#" :http-request="fileUpload" :on-remove="uploadRemove" :on-change="uploadchange" :on-exceed="uploadexceed" :file-list="uploadFile" :auto-upload="true" :limit="1" accept=".doc, .docx, .xls, .xlsx">
              <el-button slot="trigger" size="small" type="primary">上传</el-button>
              <span style="margin-left:10px;">请选择要上传的文件</span>
            </el-upload>
          </div>
        </li>
        <!-- <li>
          <div class="fill-title">解析附件：</div>
          <div class="fill-input">
            <el-switch v-model="isRecognize" active-text="是" inactive-text="否"></el-switch>
          </div>
                </li>-->
        <li class="next">
          <el-button size="large" type="primary" @click="nextstep">下一步</el-button>
          <el-button size="large" type="primary" @click="postmessage(0,'back')">保存</el-button>
          <el-button size="large" type="primary" @click="postmessage(1,'back')">提交</el-button>
        </li>
      </ul>
    </div>
    <div class="editing" v-if="stepactive == 2">
      <div class="blockname">填写内容</div>
      <div class="editorwrap">
        <div class="fill-title">文档正文</div>
        <tinymce-editor :editordata="editordata['documentbody']" @editor="editor"></tinymce-editor>
      </div>
      <div class="buttonwrap">
        <el-button size="large" type="success" @click="prevstep">上一步</el-button>
        <el-button size="large" type="primary" @click="finish">保存</el-button>
        <el-button size="large" type="primary" @click="submit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import mySteps from "./mySteps";
import TinymceEditor from "./tinymceEditor.vue";
import axios from "axios";
export default {
  components: {
    mySteps,
    TinymceEditor
  },
  inject: ["user", "obj"],
  data() {
    return {
      stepactive: 1,
      knowledgeId: "",
      knowledgeName: "",
      knowledgeType: 0,
      knowledgePastTime: "",
      knowledgeDesc: "",
      knowledgeStatus: 0,
      knowledgeExamineUserId: "",
      uploadFile: [],
      files: {},
      isRecognize: false,
      editordata: {
        documentbody: {
          qeref: "documentbody",
          content: ""
        }
      },
      editsrc: [],
      gettype: "",
      knowledgeCategoryId: "",
      /**
 * {
  categoryId: 0,
  categoryLevel: 0,
  categoryName: '文档知识库',
  children: []
}
 */
      category: [],
      defaultPropscategary: {
        label: "categoryName",
        value: "categoryId",
        children: "children",
        checkStrictly: true
      },
      approver: "",
      editdetail: "",
      type: "",
      knowledgeDetailId: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      }
    };
  },
  created() {
    // 查询知识分类
    this._API
      .findall()
      .then(res => {
        this.category = res.data.data;
      })
      .catch(err => { });
    // 查询所有审批人
    this._API
      .allapprover({ regionId: this.user.regionId })
      .then(res => {
        this.approver = res.data.data;
      })
      .catch(err => { });

    this.type = this.$route.params.type;
    if (this.$route.params.type == "edit") {
      this.knowledgeId = this.$route.params.knowledgeId;
      this.knowledgeDetail(this.$route.params.knowledgeId);
    } else {
      this.knowledgeId = "";
    }
  },
  methods: {
    // 加载知识数据
    knowledgeDetail(knowledgeId) {
      this._API
        .findoneknowledge({
          knowledgeId: knowledgeId,
          userId: this.user.userId
        })
        .then(res => {
          // console.log(res.data.data)
          this.editdetail = item;
          let item = res.data.data;
          this.knowledgeName = item.knowledgeName;
          this.knowledgeType = Number(item.knowledgeType);
          this.knowledgePastTime = item.knowledgePastTime;
          this.knowledgeDesc = item.knowledgeDesc;
          this.knowledgeStatus = item.knowledgeStatus;
          this.knowledgeCategoryId = item.knowledgeCategoryId;
          this.knowledgeExamineUserId = item.knowledgeExamineUserId;
          this.getParent(this.category, this.knowledgeCategoryId);
          item.knowledgeFileName == null
            ? (this.uploadFile = [])
            : (this.uploadFile[0].name = item.knowledgeFileName);
        })
        .catch(err => { });
    },
    // 匹配知识分类
    getParent(data2, nodeId2) {
      var arrRes = [];
      // console.log(data2.length)
      if (data2.length == 0) {
        if (!!nodeId2) {
          arrRes.unshift(data2.categoryId);
        }
        this.gettype = arrRes;
        return arrRes;
      }
      let rev = (data, nodeId) => {
        for (var i = 0, length = data.length; i < length; i++) {
          let node = data[i];
          if (node.categoryId == nodeId) {
            arrRes.unshift(node.categoryId);
            rev(data2, node.categoryParentId);
            break;
          } else {
            if (!!node.children) {
              rev(node.children, nodeId);
            }
          }
        }
        return arrRes;
      };
      arrRes = rev(data2, nodeId2);
      this.gettype = arrRes;
      return arrRes;
    },
    // 选择要上传的文件
    uploadchange(file, filelist) {
      // console.log(filelist)
      this.uploadFile = filelist;
    },
    // 删除文件
    uploadRemove(file, filelist) {
      this.uploadFile = filelist;
      this.files = {};
    },
    // 上传超量
    uploadexceed(files, filelist) {
      this.$message.warning("文件上传只能有一个");
    },
    // 自定义上传
    fileUpload(file) {
      this.files = file.file;
    },
    // 下一步
    nextstep() {
      this.postmessage(0, "next");
      // this.stepactive++
    },
    // 上一步
    prevstep() {
      this.stepactive--;
      this.editordata.documentbody.content = "";
      this.editsrc = [];
    },
    // 编辑器
    editor(val) {
      this.editsrc = val.neweditsrc;
      // console.log(this.editsrc)
    },
    // 完成
    finish() {
      this.posteditor(0, "back");
    },
    // 提交
    submit() {
      this.posteditor(1, "back");
    },
    // 下一步0，完成0，提交1
    postmessage(val, type) {
      let _this = this;
      let data = new FormData();
      if (val === 0 && type == "back") {
        if (_this.knowledgeName === "" || _this.knowledgeName == null) {
          this.$message.warning("标题不能为空");
          return false;
        }
        data.set("knowledgeCategoryId", _this.knowledgeCategoryId);
        data.set(
          "knowledgeExamineUserId",
          _this.knowledgeExamineUserId
        );
        data.set("knowledgePastTime", _this.knowledgePastTime);
      } else {
        if (_this.knowledgeName === "" || _this.knowledgeName == null) {
          this.$message.warning("标题不能为空");
          return false;
        }
        if (
          _this.knowledgeCategoryId === "" ||
          _this.knowledgeCategoryId == null
        ) {
          this.$message.warning("请选择知识分类");
          return false;
        } else {
          data.set("knowledgeCategoryId", _this.knowledgeCategoryId);
        }
        if (
          _this.knowledgeExamineUserId == "" ||
          _this.knowledgeExamineUserId == null
        ) {
          this.$message.warning("请选择审批人");
          return false;
        } else {
          data.set(
            "knowledgeExamineUserId",
            _this.knowledgeExamineUserId
          );
        }
        if (
          _this.knowledgePastTime == "" ||
          _this.knowledgePastTime == null
        ) {
          this.$message.warning("请选择过期时间");
          return false;
        } else {
          data.set("knowledgePastTime", _this.knowledgePastTime);
        }
      }
      data.set("knowledgeCreaterId", _this.user.userId);
      data.set("knowledgeDesc", _this.knowledgeDesc);
      data.set("knowledgeName", _this.knowledgeName);
      data.set("knowledgeStatus", val);
      data.set("knowledgeType", _this.knowledgeType);

      // console.log(_this.files)
      if (_this.type != "addnew") {
        data.set("knowledgeId", _this.knowledgeId);
      }
      if (JSON.stringify(_this.files) != "{}") {
        data.set("uploadFile", _this.files);
      }
      // if (_this.isRecognize) {
      //   data.set('recognizeFile',_this.files)
      // }
      // return false;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      _this._API
        .addeditknowledge(data)
        .then(res => {
          // console.log(res.data)
          loading.close();
          if (type == "next") {
            if (res.data.data != -1) {
              _this.knowledgeId = res.data.data;
            }
            // 加载编辑器的内容
            _this._API
              .findoneeditorknowledge({
                knowledgeId: _this.knowledgeId
              })
              .then(re => {
                if (re.data.data != null) {
                  this.knowledgeDetailId =
                    re.data.data.knowledgeDetailId;
                  this.editordata.documentbody.content =
                    re.data.data.knowledgeDetail;
                  this.editsrc =
                    re.data.data.knowledgeDetailFileUrl ==
                      null
                      ? []
                      : JSON.parse(
                        re.data.data
                          .knowledgeDetailFileUrl
                      );
                }
                _this.stepactive++;
              })
              .catch(err => { });
          } else if (type == "back") {
            this.$router.go(-1);
          }
        })
        .catch(err => {
          loading.close();
        });
    },
    // 第二步，完成，提交
    posteditor(val, type) {
      let _this = this;

      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let datain = {
        knowledgeId: _this.knowledgeId,
        knowledgeDetail: _this.editordata.documentbody.content,
        knowledgeDetailFileUrl: JSON.stringify(_this.editsrc)
      };
      if (_this.knowledgeDetailId != "") {
        datain.knowledgeDetailId = _this.knowledgeDetailId;
      }
      // 先调保存编辑器内容的接口再调用保存知识的接口
      _this._API
        .addeditcontent(datain)
        .then(res => {
          let data = new FormData();
          data.set("knowledgeId", _this.knowledgeId);
          data.set("knowledgeStatus", val);
          data.set(
            "knowledgeExamineUserId",
            _this.knowledgeExamineUserId
          );
          // 走审核还是保存
          _this._API
            .addeditknowledge(data)
            .then(reu => {
              loading.close();
              // console.log(reu.data)
              if (type == "back") {
                _this.$router.go(-1);
              }
            })
            .catch(err => {
              loading.close();
            });
        })
        .catch(err => {
          loading.close();
        });
    },
    // 选择知识分类
    choosetype(val) {
      this.knowledgeCategoryId = val[val.length - 1];
      this.$refs.knowledgeCategory.toggleDropDownVisible();
    }
  }
};
</script>

<style lang="scss" scoped>
#uploadcontent {
  font-size: 14px;
  padding-top: 20px;
  .write {
    margin-top: 20px;
    padding: 10px 20px;
    text-align: left;
    .blockname {
      font-size: 16px;
      line-height: 50px;
    }
    ul {
      list-style: none;
      padding-left: 20px;
      li {
        display: flex;
        align-items: center;
        line-height: 50px;
        .fill-title {
          width: 75px;
        }
        .fill-input {
          width: 350px;
        }
      }
      li.textarea {
        align-items: flex-start;
        line-height: 30px;
        margin-top: 10px;
      }
      li.next {
        margin-top: 30px;
        button {
          margin-left: 100px;
          width: 120px;
        }
      }
    }
  }
  .editing {
    margin-top: 20px;
    padding: 10px 20px;
    text-align: left;
    display: inline-block;
    .blockname {
      font-size: 16px;
      line-height: 50px;
      border-bottom: 2px solid #e4e4e4;
      padding-left: 10px;
    }
    .editorwrap {
      display: flex;
      min-height: 500px;
      margin-top: 10px;
      .fill-title {
        width: 75px;
        min-width: 75px;
      }
      .edit_container {
        width: calc(100%-75px);
        min-width: 1000px;
        height: auto;
      }
    }
    .editorwrap::after {
      display: block;
      clear: both;
      content: ".";
      visibility: hidden;
      height: 0;
    }
    .buttonwrap {
      display: flex;
      align-items: center;
      margin-top: 30px;
      button {
        margin-left: 100px;
        width: 120px;
      }
    }
  }
}
</style>
